package com.vcredit.creditcat.util;

import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

import net.sf.cglib.beans.BeanCopier;


public class BeanUtil extends com.vcredit.framework.util.BeanUtil{
	
	/**
	 * NonNull：为null的值或者是基本类型为0的值不复制
	 * 先将source的所有属性值复制到target中，
	 * 然后将target的副本对象中的不为null或者基本类型不为0的属性值拷贝到target
	 * @author zhaoqi01
	 * @param source
	 * @param target
	 * @param NonNull
	 * @return
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 */
	public static <T, V> T copy(V source, T target, boolean NonZoreNull) throws InstantiationException, IllegalAccessException {
		if(!NonZoreNull) {
			return copy(source, target);
		}
		
		BeanCopier bc = BeanCopier.create(source.getClass(), target.getClass(), false);
		T tmp = (T) target.getClass().newInstance();
		copy(target, tmp);
		bc.copy(source, target, null);
		List<Map<String,Object>> list = BeanReflectUtil.getFiledsInfo(tmp);
		for (Map<String, Object> map : list) {
			Class typeClass = (Class)map.get("type");
			String fieldName = (String)map.get("name");
			Object fieldValue = map.get("value");
			if((typeClass.isPrimitive() && fieldValue.toString().equals("0"))  || null == fieldValue) {
				continue;
			}
			String setterName = "set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
			try {
				Method method = target.getClass().getMethod(setterName, typeClass);
				method.invoke(target, fieldValue);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return target;
	}
}
